<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员仪表板 - 薪资管理系统</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="dashboard-container">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>薪资管理系统</h2>
                <p>管理员控制台</p>
            </div>
            
            <div class="nav-menu">
                <div class="nav-item active" data-section="overview">
                    <i>📊</i> 系统概览
                </div>
                <div class="nav-item" data-section="employees">
                    <i>👥</i> 员工管理
                </div>
                <div class="nav-item" data-section="departments">
                    <i>🏢</i> 部门管理
                </div>
                <div class="nav-item" data-section="salaries">
                    <i>💰</i> 工资管理
                </div>
                <div class="nav-item" data-section="attendance">
                    <i>📅</i> 考勤管理
                </div>
                <div class="nav-item" data-section="reports">
                    <i>📈</i> 统计报告
                </div>
                <div class="nav-item" data-section="settings">
                    <i>⚙️</i> 系统设置
                </div>
            </div>
            
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
        
        <!-- 主内容区 -->
        <div class="main-content">
            <!-- 系统概览 -->
            <div id="overview" class="content-section active">
                <div class="header">
                    <h1>系统概览</h1>
                    <p>欢迎回来，管理员！这里是系统的整体统计信息。</p>
                </div>
                
                <div class="stats-grid">
                    <div class="stat-card">
                        <h3>总员工数</h3>
                        <div class="number" id="totalEmployees">-</div>
                        <div class="change">在职员工</div>
                    </div>
                    <div class="stat-card">
                        <h3>部门数量</h3>
                        <div class="number" id="totalDepartments">-</div>
                        <div class="change">活跃部门</div>
                    </div>
                    <div class="stat-card">
                        <h3>工资记录</h3>
                        <div class="number" id="totalSalaries">-</div>
                        <div class="change">本月发放</div>
                    </div>
                    <div class="stat-card">
                        <h3>考勤记录</h3>
                        <div class="number" id="totalAttendance">-</div>
                        <div class="change">本月统计</div>
                    </div>
                </div>
                
                <div class="content-section">
                    <h2>快速操作</h2>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 20px;">
                        <button class="btn btn-primary" onclick="showSection('employees')">添加员工</button>
                        <button class="btn btn-success" onclick="showSection('departments')">管理部门</button>
                        <button class="btn btn-warning" onclick="showSection('salaries')">工资发放</button>
                        <button class="btn btn-primary" onclick="showSection('reports')">查看报告</button>
                    </div>
                </div>
            </div>
            
            <!-- 员工管理 -->
            <div id="employees" class="content-section">
                <div class="header">
                    <h1>员工管理</h1>
                    <p>管理员工信息，包括添加、编辑和删除员工记录。</p>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <button class="btn btn-primary" onclick="showAddEmployeeForm()">添加员工</button>
                    <button class="btn btn-success" onclick="refreshEmployeeList()">刷新列表</button>
                </div>
                
                <div class="content-section">
                    <h2>员工列表</h2>
                    <div id="employeeList">
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
            
            <!-- 部门管理 -->
            <div id="departments" class="content-section">
                <div class="header">
                    <h1>部门管理</h1>
                    <p>管理公司部门信息，包括部门创建、编辑和删除。</p>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <button class="btn btn-primary" onclick="showAddDepartmentForm()">添加部门</button>
                    <button class="btn btn-success" onclick="refreshDepartmentList()">刷新列表</button>
                </div>
                
                <div class="content-section">
                    <h2>部门列表</h2>
                    <div id="departmentList">
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
            
            <!-- 工资管理 -->
            <div id="salaries" class="content-section">
                <div class="header">
                    <h1>工资管理</h1>
                    <p>管理员工工资信息，包括工资计算、发放和记录查询。</p>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <button class="btn btn-primary" onclick="showAddSalaryForm()">添加工资记录</button>
                    <button class="btn btn-success" onclick="refreshSalaryList()">刷新列表</button>
                </div>
                
                <div class="content-section">
                    <h2>工资记录</h2>
                    <div id="salaryList">
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
            
            <!-- 考勤管理 -->
            <div id="attendance" class="content-section">
                <div class="header">
                    <h1>考勤管理</h1>
                    <p>管理员工考勤信息，包括考勤记录和统计。</p>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <button class="btn btn-primary" onclick="showAddAttendanceForm()">添加考勤记录</button>
                    <button class="btn btn-success" onclick="refreshAttendanceList()">刷新列表</button>
                </div>
                
                <div class="content-section">
                    <h2>考勤记录</h2>
                    <div id="attendanceList">
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
            
            <!-- 统计报告 -->
            <div id="reports" class="content-section">
                <div class="header">
                    <h1>统计报告</h1>
                    <p>查看系统各项统计数据和报告。</p>
                </div>
                
                <div class="content-section">
                    <h2>部门员工分布</h2>
                    <div id="departmentDistribution">
                        <p>加载中...</p>
                    </div>
                </div>
                
                <div class="content-section">
                    <h2>工资发放报告</h2>
                    <div id="salaryReport">
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
            
            <!-- 系统设置 -->
            <div id="settings" class="content-section">
                <div class="header">
                    <h1>系统设置</h1>
                    <p>管理系统配置和设置。</p>
                </div>
                
                <div class="content-section">
                    <h2>系统信息</h2>
                    <div id="systemInfo">
                        <p>加载中...</p>
                    </div>
                </div>
                
                <div class="content-section">
                    <h2>数据库操作</h2>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                        <button class="btn btn-warning" onclick="backupDatabase()">备份数据库</button>
                        <button class="btn btn-danger" onclick="restoreDatabase()">恢复数据库</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 检查登录状态
        function checkAuth() {
            const token = localStorage.getItem('token');
            const role = localStorage.getItem('role');
            
            if (!token || role !== 'admin') {
                window.location.href = 'login.html';
            }
        }
        
        // 页面加载时检查认证
        checkAuth();
        
        // 导航功能
        function showSection(sectionId) {
            // 隐藏所有内容区域
            document.querySelectorAll('.content-section').forEach(section => {
                section.classList.remove('active');
            });
            
            // 显示选中的内容区域
            const targetSection = document.getElementById(sectionId);
            targetSection.classList.add('active');
            
            // 更新导航状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            
            document.querySelector(`[data-section="${sectionId}"]`).classList.add('active');
            
            // 平滑滚动到对应区域
            setTimeout(() => {
                targetSection.scrollIntoView({ 
                    behavior: 'smooth', 
                    block: 'start',
                    inline: 'nearest'
                });
            }, 100);
            
            // 加载对应数据
            loadSectionData(sectionId);
        }
        
        // 加载区域数据
        function loadSectionData(sectionId) {
            switch(sectionId) {
                case 'overview':
                    loadOverviewData();
                    break;
                case 'employees':
                    loadEmployeeList();
                    break;
                case 'departments':
                    loadDepartmentList();
                    break;
                case 'salaries':
                    loadSalaryList();
                    break;
                case 'attendance':
                    loadAttendanceList();
                    break;
                case 'reports':
                    loadReports();
                    break;
                case 'settings':
                    loadSystemInfo();
                    break;
            }
        }
        
        // 加载概览数据
        async function loadOverviewData() {
            try {
                const response = await fetch('/api/admin/statistics');
                const data = await response.json();
                
                if (data.success && data.statistics) {
                    document.getElementById('totalEmployees').textContent = data.statistics.total_employees || 0;
                    document.getElementById('totalDepartments').textContent = data.statistics.total_departments || 0;
                    document.getElementById('totalSalaries').textContent = data.statistics.total_salary_records || 0;
                    document.getElementById('totalAttendance').textContent = data.statistics.total_attendance_records || 0;
                } else {
                    console.error('加载概览数据失败:', data.message || '未知错误');
                }
            } catch (error) {
                console.error('加载概览数据失败:', error);
            }
        }
        
        // 加载员工列表
        async function loadEmployeeList() {
            try {
                const response = await fetch('/api/employees');
                const data = await response.json();
                
                if (data.success) {
                    const employeeList = document.getElementById('employeeList');
                    let html = '<table class="data-table"><thead><tr><th>员工ID</th><th>姓名</th><th>部门</th><th>性别</th><th>年龄</th><th>电话</th><th>状态</th><th>操作</th></tr></thead><tbody>';
                    
                    data.data.forEach(employee => {
                        html += `<tr>
                            <td>${employee.id}</td>
                            <td>${employee.name}</td>
                            <td>${employee.department_id}</td>
                            <td>${employee.gender}</td>
                            <td>${employee.age}</td>
                            <td>${employee.phone}</td>
                            <td>${employee.status}</td>
                            <td>
                                <button class="btn btn-warning btn-sm" onclick="editEmployee('${employee.id}')">编辑</button>
                                <button class="btn btn-danger btn-sm" onclick="deleteEmployee('${employee.id}')">删除</button>
                            </td>
                        </tr>`;
                    });
                    
                    html += '</tbody></table>';
                    employeeList.innerHTML = html;
                }
            } catch (error) {
                console.error('加载员工列表失败:', error);
            }
        }
        
        // 加载部门列表
        async function loadDepartmentList() {
            try {
                const response = await fetch('/api/departments');
                const data = await response.json();
                
                if (data.success) {
                    const departmentList = document.getElementById('departmentList');
                    let html = '<table class="data-table"><thead><tr><th>部门ID</th><th>部门名称</th><th>负责人</th><th>电话</th><th>邮箱</th><th>预算</th><th>操作</th></tr></thead><tbody>';
                    
                    data.data.forEach(department => {
                        html += `<tr>
                            <td>${department.id}</td>
                            <td>${department.name}</td>
                            <td>${department.manager}</td>
                            <td>${department.phone}</td>
                            <td>${department.email}</td>
                            <td>${department.budget}</td>
                            <td>
                                <button class="btn btn-warning btn-sm" onclick="editDepartment('${department.id}')">编辑</button>
                                <button class="btn btn-danger btn-sm" onclick="deleteDepartment('${department.id}')">删除</button>
                            </td>
                        </tr>`;
                    });
                    
                    html += '</tbody></table>';
                    departmentList.innerHTML = html;
                }
            } catch (error) {
                console.error('加载部门列表失败:', error);
            }
        }
        
        // 加载工资列表
        async function loadSalaryList() {
            try {
                const response = await fetch('/api/salaries');
                const data = await response.json();
                
                if (data.success) {
                    const salaryList = document.getElementById('salaryList');
                    let html = '<table class="data-table"><thead><tr><th>员工ID</th><th>年份</th><th>月份</th><th>基本工资</th><th>应发工资</th><th>实发工资</th><th>状态</th><th>操作</th></tr></thead><tbody>';
                    
                    data.data.forEach(salary => {
                        const salaryId = `${salary.employee_id}:${salary.year}:${salary.month}`;
                        html += `<tr>
                            <td>${salary.employee_id}</td>
                            <td>${salary.year}</td>
                            <td>${salary.month}</td>
                            <td>${salary.basic_pay}</td>
                            <td>${salary.yingfa_pay}</td>
                            <td>${salary.shifa_pay}</td>
                            <td>${salary.status}</td>
                            <td>
                                <button class="btn btn-warning btn-sm" onclick="editSalary('${salaryId}')">编辑</button>
                                <button class="btn btn-danger btn-sm" onclick="deleteSalary('${salaryId}')">删除</button>
                            </td>
                        </tr>`;
                    });
                    
                    html += '</tbody></table>';
                    salaryList.innerHTML = html;
                }
            } catch (error) {
                console.error('加载工资列表失败:', error);
            }
        }
        
        // 加载考勤列表
        async function loadAttendanceList() {
            try {
                const response = await fetch('/api/attendance');
                const data = await response.json();
                
                if (data.success) {
                    const attendanceList = document.getElementById('attendanceList');
                    let html = '<table class="data-table"><thead><tr><th>员工ID</th><th>年份</th><th>月份</th><th>出勤天数</th><th>请假天数</th><th>操作</th></tr></thead><tbody>';
                    
                    data.data.forEach(attendance => {
                        const attendanceId = `${attendance.employee_id}:${attendance.year}:${attendance.month}`;
                        html += `<tr>
                            <td>${attendance.employee_id}</td>
                            <td>${attendance.year}</td>
                            <td>${attendance.month}</td>
                            <td>${attendance.attendance_days}</td>
                            <td>${attendance.leave_days}</td>
                            <td>
                                <button class="btn btn-warning btn-sm" onclick="editAttendance('${attendanceId}')">编辑</button>
                                <button class="btn btn-danger btn-sm" onclick="deleteAttendance('${attendanceId}')">删除</button>
                            </td>
                        </tr>`;
                    });
                    
                    html += '</tbody></table>';
                    attendanceList.innerHTML = html;
                }
            } catch (error) {
                console.error('加载考勤列表失败:', error);
            }
        }
        
        // 加载报告
        async function loadReports() {
            try {
                const response = await fetch('/api/admin/reports');
                const data = await response.json();
                
                if (data.success) {
                    // 部门分布
                    const deptDist = document.getElementById('departmentDistribution');
                    let deptHtml = '<table class="data-table"><thead><tr><th>部门名称</th><th>员工数量</th></tr></thead><tbody>';
                    
                    if (data.reports.department_employee_stats) {
                        data.reports.department_employee_stats.forEach(dept => {
                            deptHtml += `<tr><td>${dept.department_name}</td><td>${dept.employee_count}</td></tr>`;
                        });
                    }
                    
                    deptHtml += '</tbody></table>';
                    deptDist.innerHTML = deptHtml;
                    
                    // 工资报告
                    const salaryReport = document.getElementById('salaryReport');
                    let salaryHtml = '<table class="data-table"><thead><tr><th>年份</th><th>月份</th><th>员工数量</th><th>总发放金额</th></tr></thead><tbody>';
                    
                    if (data.reports.salary_stats) {
                        data.reports.salary_stats.forEach(salary => {
                            salaryHtml += `<tr><td>${salary.year}</td><td>${salary.month}</td><td>${salary.employee_count}</td><td>${salary.total_paid}</td></tr>`;
                        });
                    }
                    
                    salaryHtml += '</tbody></table>';
                    salaryReport.innerHTML = salaryHtml;
                }
            } catch (error) {
                console.error('加载报告失败:', error);
                document.getElementById('departmentDistribution').innerHTML = '<p style="color: red;">加载报告失败: ' + error.message + '</p>';
                document.getElementById('salaryReport').innerHTML = '<p style="color: red;">加载报告失败: ' + error.message + '</p>';
            }
        }
        
        // 加载系统信息
        async function loadSystemInfo() {
            try {
                const response = await fetch('/api/admin/system-info');
                const data = await response.json();
                
                if (data.success) {
                    const systemInfo = document.getElementById('systemInfo');
                    let html = '<table class="data-table"><tbody>';
                    
                    if (data.system_info) {
                        for (const [key, value] of Object.entries(data.system_info)) {
                            html += `<tr><td><strong>${key}</strong></td><td>${value}</td></tr>`;
                        }
                    }
                    
                    html += '</tbody></table>';
                    systemInfo.innerHTML = html;
                } else {
                    document.getElementById('systemInfo').innerHTML = '<p style="color: red;">加载系统信息失败: ' + (data.message || '未知错误') + '</p>';
                }
            } catch (error) {
                console.error('加载系统信息失败:', error);
                document.getElementById('systemInfo').innerHTML = '<p style="color: red;">加载系统信息失败: ' + error.message + '</p>';
            }
        }
        
        // 刷新函数
        function refreshEmployeeList() { loadEmployeeList(); }
        function refreshDepartmentList() { loadDepartmentList(); }
        function refreshSalaryList() { loadSalaryList(); }
        function refreshAttendanceList() { loadAttendanceList(); }
        
        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('role');
            localStorage.removeItem('username');
            window.location.href = 'login.html';
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定导航事件
            document.querySelectorAll('.nav-item').forEach(item => {
                item.addEventListener('click', function() {
                    const sectionId = this.dataset.section;
                    showSection(sectionId);
                });
            });
            
            // 加载初始数据
            loadOverviewData();
        });
        
        // 员工管理功能
        function showAddEmployeeForm() {
            const formHtml = `
                <div class="modal" id="addEmployeeModal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>添加员工</h3>
                            <span class="close" onclick="closeModal('addEmployeeModal')">&times;</span>
                        </div>
                        <div class="modal-body">
                            <form id="addEmployeeForm">
                                <div class="form-group">
                                    <label>员工ID:</label>
                                    <input type="text" id="employeeId" required>
                                </div>
                                <div class="form-group">
                                    <label>姓名:</label>
                                    <input type="text" id="employeeName" required>
                                </div>
                                <div class="form-group">
                                    <label>部门ID:</label>
                                    <input type="text" id="employeeDept" required>
                                </div>
                                <div class="form-group">
                                    <label>性别:</label>
                                    <select id="employeeGender" required>
                                        <option value="男">男</option>
                                        <option value="女">女</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>年龄:</label>
                                    <input type="number" id="employeeAge" required>
                                </div>
                                <div class="form-group">
                                    <label>电话:</label>
                                    <input type="text" id="employeePhone" required>
                                </div>
                                <div class="form-group">
                                    <label>入职年份:</label>
                                    <input type="number" id="employeeHireYear" required>
                                </div>
                                <div class="form-group">
                                    <label>状态:</label>
                                    <select id="employeeStatus" required>
                                        <option value="在职">在职</option>
                                        <option value="离职">离职</option>
                                    </select>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" class="btn btn-primary">添加</button>
                                    <button type="button" class="btn btn-secondary" onclick="closeModal('addEmployeeModal')">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', formHtml);
            document.getElementById('addEmployeeModal').style.display = 'block';
            
            document.getElementById('addEmployeeForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const employeeData = {
                    id: document.getElementById('employeeId').value,
                    name: document.getElementById('employeeName').value,
                    department_id: document.getElementById('employeeDept').value,
                    gender: document.getElementById('employeeGender').value,
                    age: document.getElementById('employeeAge').value,
                    phone: document.getElementById('employeePhone').value,
                    hire_year: document.getElementById('employeeHireYear').value,
                    status: document.getElementById('employeeStatus').value
                };
                
                try {
                    const response = await fetch('/api/employees', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(employeeData)
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('员工添加成功！');
                        closeModal('addEmployeeModal');
                        loadEmployeeList();
                    } else {
                        alert('添加失败: ' + result.message);
                    }
                } catch (error) {
                    alert('添加失败: ' + error.message);
                }
            });
        }
        
        async function editEmployee(id) {
            try {
                console.log('正在获取员工信息，ID:', id);
                const response = await fetch(`/api/employees/${id}`);
                console.log('响应状态:', response.status);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const text = await response.text();
                console.log('响应文本:', text);
                
                if (!text.trim()) {
                    throw new Error('服务器返回空响应');
                }
                
                const data = JSON.parse(text);
                console.log('解析后的数据:', data);
                
                if (data.success) {
                    const employee = data.data;
                    const formHtml = `
                        <div class="modal" id="editEmployeeModal">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h3>编辑员工</h3>
                                    <span class="close" onclick="closeModal('editEmployeeModal')">&times;</span>
                                </div>
                                <div class="modal-body">
                                    <form id="editEmployeeForm">
                                        <div class="form-group">
                                            <label>员工ID:</label>
                                            <input type="text" id="editEmployeeId" value="${employee.id}" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label>姓名:</label>
                                            <input type="text" id="editEmployeeName" value="${employee.name}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>部门ID:</label>
                                            <input type="text" id="editEmployeeDept" value="${employee.department_id}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>性别:</label>
                                            <select id="editEmployeeGender" required>
                                                <option value="男" ${employee.gender === '男' ? 'selected' : ''}>男</option>
                                                <option value="女" ${employee.gender === '女' ? 'selected' : ''}>女</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>年龄:</label>
                                            <input type="number" id="editEmployeeAge" value="${employee.age}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>电话:</label>
                                            <input type="text" id="editEmployeePhone" value="${employee.phone}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>入职年份:</label>
                                            <input type="number" id="editEmployeeHireYear" value="${employee.hire_year}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>状态:</label>
                                            <select id="editEmployeeStatus" required>
                                                <option value="在职" ${employee.status === '在职' ? 'selected' : ''}>在职</option>
                                                <option value="离职" ${employee.status === '离职' ? 'selected' : ''}>离职</option>
                                            </select>
                                        </div>
                                        <div class="form-actions">
                                            <button type="submit" class="btn btn-primary">更新</button>
                                            <button type="button" class="btn btn-secondary" onclick="closeModal('editEmployeeModal')">取消</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    document.body.insertAdjacentHTML('beforeend', formHtml);
                    document.getElementById('editEmployeeModal').style.display = 'block';
                    
                    document.getElementById('editEmployeeForm').addEventListener('submit', async function(e) {
                        e.preventDefault();
                        
                        const employeeData = {
                            name: document.getElementById('editEmployeeName').value,
                            department_id: document.getElementById('editEmployeeDept').value,
                            gender: document.getElementById('editEmployeeGender').value,
                            age: document.getElementById('editEmployeeAge').value,
                            phone: document.getElementById('editEmployeePhone').value,
                            hire_year: document.getElementById('editEmployeeHireYear').value,
                            status: document.getElementById('editEmployeeStatus').value
                        };
                        
                        try {
                            const response = await fetch(`/api/employees/${id}`, {
                                method: 'PUT',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(employeeData)
                            });
                            
                            const result = await response.json();
                            if (result.success) {
                                alert('员工信息更新成功！');
                                closeModal('editEmployeeModal');
                                loadEmployeeList();
                            } else {
                                alert('更新失败: ' + result.message);
                            }
                        } catch (error) {
                            alert('更新失败: ' + error.message);
                        }
                    });
                } else {
                    alert('获取员工信息失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('编辑员工错误:', error);
                alert('加载员工信息失败: ' + error.message);
            }
        }
        
        async function deleteEmployee(id) {
            if (confirm('确定要删除这个员工吗？')) {
                try {
                    const response = await fetch(`/api/employees/${id}`, {
                        method: 'DELETE'
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('员工删除成功！');
                        loadEmployeeList();
                    } else {
                        alert('删除失败: ' + result.message);
                    }
                } catch (error) {
                    alert('删除失败: ' + error.message);
                }
            }
        }
        
        // 部门管理功能
        function showAddDepartmentForm() {
            const formHtml = `
                <div class="modal" id="addDepartmentModal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>添加部门</h3>
                            <span class="close" onclick="closeModal('addDepartmentModal')">&times;</span>
                        </div>
                        <div class="modal-body">
                            <form id="addDepartmentForm">
                                <div class="form-group">
                                    <label>部门ID:</label>
                                    <input type="text" id="departmentId" required>
                                </div>
                                <div class="form-group">
                                    <label>部门名称:</label>
                                    <input type="text" id="departmentName" required>
                                </div>
                                <div class="form-group">
                                    <label>负责人:</label>
                                    <input type="text" id="departmentManager" required>
                                </div>
                                <div class="form-group">
                                    <label>电话:</label>
                                    <input type="text" id="departmentPhone" required>
                                </div>
                                <div class="form-group">
                                    <label>邮箱:</label>
                                    <input type="email" id="departmentEmail" required>
                                </div>
                                <div class="form-group">
                                    <label>地址:</label>
                                    <input type="text" id="departmentAddress" required>
                                </div>
                                <div class="form-group">
                                    <label>预算:</label>
                                    <input type="number" id="departmentBudget" required>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" class="btn btn-primary">添加</button>
                                    <button type="button" class="btn btn-secondary" onclick="closeModal('addDepartmentModal')">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', formHtml);
            document.getElementById('addDepartmentModal').style.display = 'block';
            
            document.getElementById('addDepartmentForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const departmentData = {
                    id: document.getElementById('departmentId').value,
                    name: document.getElementById('departmentName').value,
                    manager: document.getElementById('departmentManager').value,
                    phone: document.getElementById('departmentPhone').value,
                    email: document.getElementById('departmentEmail').value,
                    address: document.getElementById('departmentAddress').value,
                    budget: document.getElementById('departmentBudget').value
                };
                
                try {
                    const response = await fetch('/api/departments', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(departmentData)
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('部门添加成功！');
                        closeModal('addDepartmentModal');
                        loadDepartmentList();
                    } else {
                        alert('添加失败: ' + result.message);
                    }
                } catch (error) {
                    alert('添加失败: ' + error.message);
                }
            });
        }
        
        async function editDepartment(id) {
            try {
                console.log('正在获取部门信息，ID:', id);
                const response = await fetch(`/api/departments/${id}`);
                console.log('响应状态:', response.status);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const text = await response.text();
                console.log('响应文本:', text);
                
                if (!text.trim()) {
                    throw new Error('服务器返回空响应');
                }
                
                const data = JSON.parse(text);
                console.log('解析后的数据:', data);
                
                if (data.success) {
                    const department = data.data;
                    const formHtml = `
                        <div class="modal" id="editDepartmentModal">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h3>编辑部门</h3>
                                    <span class="close" onclick="closeModal('editDepartmentModal')">&times;</span>
                                </div>
                                <div class="modal-body">
                                    <form id="editDepartmentForm">
                                        <div class="form-group">
                                            <label>部门ID:</label>
                                            <input type="text" id="editDepartmentId" value="${department.id}" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label>部门名称:</label>
                                            <input type="text" id="editDepartmentName" value="${department.name}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>负责人:</label>
                                            <input type="text" id="editDepartmentManager" value="${department.manager}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>电话:</label>
                                            <input type="text" id="editDepartmentPhone" value="${department.phone}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>邮箱:</label>
                                            <input type="email" id="editDepartmentEmail" value="${department.email}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>地址:</label>
                                            <input type="text" id="editDepartmentAddress" value="${department.address}" required>
                                        </div>
                                        <div class="form-group">
                                            <label>预算:</label>
                                            <input type="number" id="editDepartmentBudget" value="${department.budget}" required>
                                        </div>
                                        <div class="form-actions">
                                            <button type="submit" class="btn btn-primary">更新</button>
                                            <button type="button" class="btn btn-secondary" onclick="closeModal('editDepartmentModal')">取消</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    document.body.insertAdjacentHTML('beforeend', formHtml);
                    document.getElementById('editDepartmentModal').style.display = 'block';
                    
                    document.getElementById('editDepartmentForm').addEventListener('submit', async function(e) {
                        e.preventDefault();
                        
                        const departmentData = {
                            name: document.getElementById('editDepartmentName').value,
                            manager: document.getElementById('editDepartmentManager').value,
                            phone: document.getElementById('editDepartmentPhone').value,
                            email: document.getElementById('editDepartmentEmail').value,
                            address: document.getElementById('editDepartmentAddress').value,
                            budget: document.getElementById('editDepartmentBudget').value
                        };
                        
                        try {
                            const response = await fetch(`/api/departments/${id}`, {
                                method: 'PUT',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(departmentData)
                            });
                            
                            const result = await response.json();
                            if (result.success) {
                                alert('部门信息更新成功！');
                                closeModal('editDepartmentModal');
                                loadDepartmentList();
                            } else {
                                alert('更新失败: ' + result.message);
                            }
                        } catch (error) {
                            alert('更新失败: ' + error.message);
                        }
                    });
                } else {
                    alert('获取部门信息失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('编辑部门错误:', error);
                alert('加载部门信息失败: ' + error.message);
            }
        }
        
        async function deleteDepartment(id) {
            if (confirm('确定要删除这个部门吗？')) {
                try {
                    const response = await fetch(`/api/departments/${id}`, {
                        method: 'DELETE'
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('部门删除成功！');
                        loadDepartmentList();
                    } else {
                        alert('删除失败: ' + result.message);
                    }
                } catch (error) {
                    alert('删除失败: ' + error.message);
                }
            }
        }
        
        // 工资管理功能
        function showAddSalaryForm() {
            const formHtml = `
                <div class="modal" id="addSalaryModal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>添加工资记录</h3>
                            <span class="close" onclick="closeModal('addSalaryModal')">&times;</span>
                        </div>
                        <div class="modal-body">
                            <form id="addSalaryForm">
                                <div class="form-group">
                                    <label>员工ID:</label>
                                    <input type="text" id="salaryEmployeeId" required>
                                </div>
                                <div class="form-group">
                                    <label>年份:</label>
                                    <input type="number" id="salaryYear" required>
                                </div>
                                <div class="form-group">
                                    <label>月份:</label>
                                    <input type="number" id="salaryMonth" min="1" max="12" required>
                                </div>
                                <div class="form-group">
                                    <label>基本工资:</label>
                                    <input type="number" id="salaryBasicPay" required>
                                </div>
                                <div class="form-group">
                                    <label>应发工资:</label>
                                    <input type="number" id="salaryYingfaPay" required>
                                </div>
                                <div class="form-group">
                                    <label>补贴:</label>
                                    <input type="number" id="salaryButiePay" required>
                                </div>
                                <div class="form-group">
                                    <label>扣除:</label>
                                    <input type="number" id="salaryKouchuPay" required>
                                </div>
                                <div class="form-group">
                                    <label>实发工资:</label>
                                    <input type="number" id="salaryShifaPay" required>
                                </div>
                                <div class="form-group">
                                    <label>状态:</label>
                                    <select id="salaryStatus" required>
                                        <option value="已发放">已发放</option>
                                        <option value="未发放">未发放</option>
                                    </select>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" class="btn btn-primary">添加</button>
                                    <button type="button" class="btn btn-secondary" onclick="closeModal('addSalaryModal')">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', formHtml);
            document.getElementById('addSalaryModal').style.display = 'block';
            
            document.getElementById('addSalaryForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const salaryData = {
                    employee_id: document.getElementById('salaryEmployeeId').value,
                    year: document.getElementById('salaryYear').value,
                    month: document.getElementById('salaryMonth').value,
                    basic_pay: document.getElementById('salaryBasicPay').value,
                    yingfa_pay: document.getElementById('salaryYingfaPay').value,
                    butie_pay: document.getElementById('salaryButiePay').value,
                    kouchu_pay: document.getElementById('salaryKouchuPay').value,
                    shifa_pay: document.getElementById('salaryShifaPay').value,
                    status: document.getElementById('salaryStatus').value
                };
                
                try {
                    const response = await fetch('/api/salaries', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(salaryData)
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('工资记录添加成功！');
                        closeModal('addSalaryModal');
                        loadSalaryList();
                    } else {
                        alert('添加失败: ' + result.message);
                    }
                } catch (error) {
                    alert('添加失败: ' + error.message);
                }
            });
        }
        
        // 考勤管理功能
        function showAddAttendanceForm() {
            const formHtml = `
                <div class="modal" id="addAttendanceModal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>添加考勤记录</h3>
                            <span class="close" onclick="closeModal('addAttendanceModal')">&times;</span>
                        </div>
                        <div class="modal-body">
                            <form id="addAttendanceForm">
                                <div class="form-group">
                                    <label>员工ID:</label>
                                    <input type="text" id="attendanceEmployeeId" required>
                                </div>
                                <div class="form-group">
                                    <label>年份:</label>
                                    <input type="number" id="attendanceYear" required>
                                </div>
                                <div class="form-group">
                                    <label>月份:</label>
                                    <input type="number" id="attendanceMonth" min="1" max="12" required>
                                </div>
                                <div class="form-group">
                                    <label>出勤天数:</label>
                                    <input type="number" id="attendanceDays" min="0" max="31" required>
                                </div>
                                <div class="form-group">
                                    <label>请假天数:</label>
                                    <input type="number" id="attendanceLeaveDays" min="0" max="31" required>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" class="btn btn-primary">添加</button>
                                    <button type="button" class="btn btn-secondary" onclick="closeModal('addAttendanceModal')">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', formHtml);
            document.getElementById('addAttendanceModal').style.display = 'block';
            
            document.getElementById('addAttendanceForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const attendanceData = {
                    employee_id: document.getElementById('attendanceEmployeeId').value,
                    year: document.getElementById('attendanceYear').value,
                    month: document.getElementById('attendanceMonth').value,
                    attendance_days: document.getElementById('attendanceDays').value,
                    leave_days: document.getElementById('attendanceLeaveDays').value
                };
                
                try {
                    const response = await fetch('/api/attendance', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(attendanceData)
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('考勤记录添加成功！');
                        closeModal('addAttendanceModal');
                        loadAttendanceList();
                    } else {
                        alert('添加失败: ' + result.message);
                    }
                } catch (error) {
                    alert('添加失败: ' + error.message);
                }
            });
        }
        
        // 通用功能
        function closeModal(modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.remove();
            }
        }
        
        // 数据库操作功能
        function backupDatabase() {
            alert('数据库备份功能需要服务器端实现');
        }
        
        function restoreDatabase() {
            alert('数据库恢复功能需要服务器端实现');
        }
        
        // 工资编辑和删除功能
        async function editSalary(id) {
            // 解析复合主键
            const parts = id.split(':');
            if (parts.length !== 3) {
                alert('无效的工资记录ID');
                return;
            }
            
            const [employee_id, year, month] = parts;
            
            // 这里简化处理，直接显示编辑表单
            const formHtml = `
                <div class="modal" id="editSalaryModal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>编辑工资记录</h3>
                            <span class="close" onclick="closeModal('editSalaryModal')">&times;</span>
                        </div>
                        <div class="modal-body">
                            <form id="editSalaryForm">
                                <div class="form-group">
                                    <label>员工ID:</label>
                                    <input type="text" id="editSalaryEmployeeId" value="${employee_id}" readonly>
                                </div>
                                <div class="form-group">
                                    <label>年份:</label>
                                    <input type="number" id="editSalaryYear" value="${year}" readonly>
                                </div>
                                <div class="form-group">
                                    <label>月份:</label>
                                    <input type="number" id="editSalaryMonth" value="${month}" readonly>
                                </div>
                                <div class="form-group">
                                    <label>基本工资:</label>
                                    <input type="number" id="editSalaryBasicPay" required>
                                </div>
                                <div class="form-group">
                                    <label>应发工资:</label>
                                    <input type="number" id="editSalaryYingfaPay" required>
                                </div>
                                <div class="form-group">
                                    <label>补贴:</label>
                                    <input type="number" id="editSalaryButiePay" required>
                                </div>
                                <div class="form-group">
                                    <label>扣除:</label>
                                    <input type="number" id="editSalaryKouchuPay" required>
                                </div>
                                <div class="form-group">
                                    <label>实发工资:</label>
                                    <input type="number" id="editSalaryShifaPay" required>
                                </div>
                                <div class="form-group">
                                    <label>状态:</label>
                                    <select id="editSalaryStatus" required>
                                        <option value="已发放">已发放</option>
                                        <option value="未发放">未发放</option>
                                    </select>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" class="btn btn-primary">更新</button>
                                    <button type="button" class="btn btn-secondary" onclick="closeModal('editSalaryModal')">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', formHtml);
            document.getElementById('editSalaryModal').style.display = 'block';
            
            document.getElementById('editSalaryForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const salaryData = {
                    basic_pay: document.getElementById('editSalaryBasicPay').value,
                    yingfa_pay: document.getElementById('editSalaryYingfaPay').value,
                    butie_pay: document.getElementById('editSalaryButiePay').value,
                    kouchu_pay: document.getElementById('editSalaryKouchuPay').value,
                    shifa_pay: document.getElementById('editSalaryShifaPay').value,
                    status: document.getElementById('editSalaryStatus').value
                };
                
                try {
                    const response = await fetch(`/api/salaries/${id}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(salaryData)
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('工资记录更新成功！');
                        closeModal('editSalaryModal');
                        loadSalaryList();
                    } else {
                        alert('更新失败: ' + result.message);
                    }
                } catch (error) {
                    alert('更新失败: ' + error.message);
                }
            });
        }
        
        async function deleteSalary(id) {
            if (confirm('确定要删除这个工资记录吗？')) {
                try {
                    const response = await fetch(`/api/salaries/${id}`, {
                        method: 'DELETE'
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('工资记录删除成功！');
                        loadSalaryList();
                    } else {
                        alert('删除失败: ' + result.message);
                    }
                } catch (error) {
                    alert('删除失败: ' + error.message);
                }
            }
        }
        
        // 考勤编辑和删除功能
        async function editAttendance(id) {
            // 解析复合主键
            const parts = id.split(':');
            if (parts.length !== 3) {
                alert('无效的考勤记录ID');
                return;
            }
            
            const [employee_id, year, month] = parts;
            
            // 这里简化处理，直接显示编辑表单
            const formHtml = `
                <div class="modal" id="editAttendanceModal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>编辑考勤记录</h3>
                            <span class="close" onclick="closeModal('editAttendanceModal')">&times;</span>
                        </div>
                        <div class="modal-body">
                            <form id="editAttendanceForm">
                                <div class="form-group">
                                    <label>员工ID:</label>
                                    <input type="text" id="editAttendanceEmployeeId" value="${employee_id}" readonly>
                                </div>
                                <div class="form-group">
                                    <label>年份:</label>
                                    <input type="number" id="editAttendanceYear" value="${year}" readonly>
                                </div>
                                <div class="form-group">
                                    <label>月份:</label>
                                    <input type="number" id="editAttendanceMonth" value="${month}" readonly>
                                </div>
                                <div class="form-group">
                                    <label>出勤天数:</label>
                                    <input type="number" id="editAttendanceDays" min="0" max="31" required>
                                </div>
                                <div class="form-group">
                                    <label>请假天数:</label>
                                    <input type="number" id="editAttendanceLeaveDays" min="0" max="31" required>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" class="btn btn-primary">更新</button>
                                    <button type="button" class="btn btn-secondary" onclick="closeModal('editAttendanceModal')">取消</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', formHtml);
            document.getElementById('editAttendanceModal').style.display = 'block';
            
            document.getElementById('editAttendanceForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const attendanceData = {
                    attendance_days: document.getElementById('editAttendanceDays').value,
                    leave_days: document.getElementById('editAttendanceLeaveDays').value
                };
                
                try {
                    const response = await fetch(`/api/attendance/${id}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(attendanceData)
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('考勤记录更新成功！');
                        closeModal('editAttendanceModal');
                        loadAttendanceList();
                    } else {
                        alert('更新失败: ' + result.message);
                    }
                } catch (error) {
                    alert('更新失败: ' + error.message);
                }
            });
        }
        
        async function deleteAttendance(id) {
            if (confirm('确定要删除这个考勤记录吗？')) {
                try {
                    const response = await fetch(`/api/attendance/${id}`, {
                        method: 'DELETE'
                    });
                    
                    const result = await response.json();
                    if (result.success) {
                        alert('考勤记录删除成功！');
                        loadAttendanceList();
                    } else {
                        alert('删除失败: ' + result.message);
                    }
                } catch (error) {
                    alert('删除失败: ' + error.message);
                }
            }
        }
    </script>
</body>
</html>
